package io.github.jyrmc.gmcp.utils

import io.github.jyrmc.gmcp.entity.ColumnEntity
import io.github.jyrmc.gmcp.generate.GenerateMarkdown
import freemarker.template.Configuration
import freemarker.template.DefaultObjectWrapper
import java.util.*


/**
 * 创建于 2020-01-08 18:16
 *
 * @author jiangyun
 * @类说明：生成markdown文档
 */

object GenerateMarkdownUtil {


    /**
     * 导出markdown文档
     * @param dbType                数据类型(如：mysql、postgresql)
     * @param url                   数据库连接地址
     * @param databaseName          数据库名称
     * @param userName              用户名
     * @param password              密码
     * @param projectPath           文件生成目录
     */
    @Throws(Exception::class)
    fun export(
        dbType: String,
        url: String,
        databaseName: String,
        userName: String,
        password: String,
        projectPath: String
    ) {
        val tables = when (dbType) {
            "mysql" -> MysqlDatabaseUtil.getAllTableInfo(url, databaseName, userName, password)
            // "postgresql" -> PostgresqlDatabaseUtil.getTableInfo(url, userName, password, it)
            else -> null
        } ?: return

        var columns: MutableList<ColumnEntity>?
        var pkColumns: MutableList<ColumnEntity>?
        var uniColumns: MutableList<ColumnEntity>?
        var mulColumns: MutableList<ColumnEntity>?
        for (index in 0 until tables.size) {
            // 获取表列
            columns = when (dbType) {
                "mysql" -> MysqlDatabaseUtil.findTableColumns(
                    url,
                    databaseName,
                    userName,
                    password,
                    tables[index].tableName!!
                )
                "postgresql" -> PostgresqlDatabaseUtil.findTableColumns(
                    url,
                    userName,
                    password,
                    tables[index].tableName!!
                )
                else -> null
            }

            // 初始化主键列数组
            pkColumns = mutableListOf()
            uniColumns = mutableListOf()
            mulColumns = mutableListOf()
            for (subIndex in 0 until columns!!.size) {// 处理一些值及默认数据
                columns[subIndex].attrName = UnderlineToCamelUtil.underlineToCamel(columns[subIndex].columnName!!, true)
                columns[subIndex].upcaseAttrName = UnderlineToCamelUtil.firstCharToUpcaseOrLowcase(columns[subIndex].attrName!!, false)
                columns[subIndex].required = columns[subIndex].isNullable == "NO"

                // 处理主键列
                if (!columns[subIndex].columnKey.isNullOrBlank() && columns[subIndex].columnKey == "PRI") {
                    pkColumns.add(columns[subIndex])
                }

                // 处理唯一值列
                if (!columns[subIndex].columnKey.isNullOrBlank() && columns[subIndex].columnKey == "UNI") {
                    uniColumns.add(columns[subIndex])
                }

                // 处理索引列
                if (!columns[subIndex].columnKey.isNullOrBlank() && columns[subIndex].columnKey == "MUL") {
                    mulColumns.add(columns[subIndex])
                }
            }
            tables[index].columns = columns
            tables[index].pkColumns = pkColumns
            tables[index].uniColumns = uniColumns
            tables[index].mulColumns = mulColumns
        }

        val config = Configuration(Configuration.VERSION_2_3_23)
        config.setClassLoaderForTemplateLoading(this@GenerateMarkdownUtil.javaClass.classLoader, "templates/")
        config.setEncoding(Locale.CHINA, "utf-8")
        config.objectWrapper = DefaultObjectWrapper()

        val docMap: MutableMap<String, Any?> = mutableMapOf()
        docMap["title"] = databaseName
        docMap["description"] = "这是导出的markdown数据库设计文档，如需其他类型的文档(word)，可以将此文档进行转换其他类型的即可。"
        docMap["tableList"] = tables

        // 生成文档
        GenerateMarkdown.freemarkerGenerate(config, projectPath, docMap, databaseName)

        println("====================>>>>>>>>>>>>>>>>>>> generate doc success!!! <<<<<<<<<<<<<<====================")
    }
}
